//
//  Extensions.swift
//  GifUsage
//
//  Created by Ting Han on 2020/12/18.
//  Copyright © 2020 Ting Han. All rights reserved.
//

import UIKit

extension Array {
    subscript (safe index: Int) -> Element? {
        return indices ~= index ? self[index] : nil
    }
}

extension UIImage {
    func resized(to size: CGSize) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
        draw(in: CGRect(origin: .zero, size: size))
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image ?? self
    }
    
    func constrained(by constrainingSize: CGSize) -> UIImage {
        let newSize = size.constrained(by: constrainingSize)
        return resized(to: newSize)
    }
    
    func filling(size fillingSize: CGSize) -> UIImage {
        let newSize = size.filling(fillingSize)
        return resized(to: newSize)
    }
    
    class func image(with data: Data, size: CGSize) -> UIImage? {
        return UIImage(data: data)?.resized(to: size)
    }
    
    class func size(withImageData data: Data) -> CGSize? {
        return UIImage(data: data)?.size
    }
}

extension CGSize {
    var aspectRatio: CGFloat {
        if height == 0 { return 1 }
        return width / height
    }
    
    func constrained(by size: CGSize) -> CGSize {
        let aspectWidth = round(aspectRatio * size.height)
        let aspectHeight = round(size.width / aspectRatio)
        
        if aspectWidth > size.width {
            return CGSize(width: size.width, height: aspectHeight)
        } else {
            return CGSize(width: aspectWidth, height: size.height)
        }
    }
    
    func filling(_ size: CGSize) -> CGSize {
        let aspectWidth = round(aspectRatio * size.height)
        let aspectHeight = round(size.width / aspectRatio)
        
        if aspectWidth > size.width {
            return CGSize(width: aspectWidth, height: size.height)
        } else {
            return CGSize(width: size.width, height: aspectHeight)
        }
    }
}

